package com.itheima.service.store.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.domain.store.Question;
import com.itheima.factory.MapperFactory;
import com.itheima.mapper.store.QuestionMapper;
import com.itheima.service.store.QuestionService;
import com.itheima.utils.TransactionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 部门 业务层 实现
 */
public class QuestionServiceImpl implements QuestionService {
    @Override
    public Page<Question> findAll(String pageNum, String pageSize) {
        //获取sqlSession对象
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //配置分页信息
        int num = 1;
        int size = 10;
        //阿帕奇的StringUtils.isNotBlank() 可以同时判断空, 无值, 空格
        if (StringUtils.isNotBlank(pageNum)) {
            num = Integer.parseInt(pageNum);
        }
        if (StringUtils.isNotBlank(pageSize)) {
            size = Integer.parseInt(pageSize);
        }
        Page<Question> page = PageHelper.startPage(num, size);
        //查找全部
        mapper.findAll();
        //释放资源
        TransactionUtil.close(sqlSession);

        return page;
    }

    @Override
    public List<Question> findAll() {
        //获取sqlSession对象
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //查找全部
        Page<Question> list = mapper.findAll();
        //释放资源
        TransactionUtil.close(sqlSession);

        return list;
    }

    @Override
    public void addQuestion(Question question) {
        //获取sqlSession对象
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //查找全部
        mapper.addQuestion(question);
        //提交事务
        TransactionUtil.commit(sqlSession);
        //释放资源
        TransactionUtil.close(sqlSession);

    }

    @Override
    public boolean deleteByIds(String ids) {
        try {
            SqlSession sqlSession = MapperFactory.getSqlSession();
            //获取映射对象
            QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
            //ids处理
            String[] idArr = ids.split(",");
            mapper.deleteByIds(idArr);
            //提交事务
            TransactionUtil.commit(sqlSession);
            //释放资源
            TransactionUtil.close(sqlSession);

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @Override
    public Question findById(String id) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //查找用户
        Question question = mapper.findById(id);
        //释放资源
        TransactionUtil.close(sqlSession);
        return question;
    }

    @Override
    public void updateQuestion(Question question) {
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //更新信息
        mapper.updateQuestion(question);
        //提交事务
        TransactionUtil.commit(sqlSession);
        //释放资源
        TransactionUtil.close(sqlSession);
    }

    @Override
    public String save(Question question, boolean flag) {
        SqlSession sqlSession = null;
        try {
            sqlSession = MapperFactory.getSqlSession();
            //获取映射对象
            QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
            //获取uuid并设置
            String id = UUID.randomUUID().toString().replace("-", "");
            question.setId(id);
            //设置审核属性 未审核
            question.setReviewStatus("0");
            //设置创建日期
            question.setCreateTime(new Date());
            //如果上传了图片 设置图片属性
            if (flag) {
                question.setPicture(id);
            }
            //保存
            mapper.save(question);
            //提交事务
            TransactionUtil.commit(sqlSession);
            return id;
        } catch (Exception e) {
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
        } finally {
            try {
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 数据导表 返回表的输出流对象
     *
     * @return
     */
    @Override
    public ByteArrayOutputStream getReport() {
        //获取sqlSession对象
        SqlSession sqlSession = MapperFactory.getSqlSession();
        //获取映射对象
        QuestionMapper mapper = MapperFactory.getMapper(sqlSession, QuestionMapper.class);
        //查找全部
        List<Question> list = mapper.findAll();
        //释放资源
        TransactionUtil.close(sqlSession);

        //创建excel工作簿文件对象
        Workbook wb = new XSSFWorkbook();
        //创建工作表
        Sheet sheet = wb.createSheet("题目数据");

        //单元格格式设置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);  //水平居中
        //上下左右边界线
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);

        //标题合并单元格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 12));
        Row row_1 = sheet.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("在线试题导出信息");
        //创建标题样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);

        //制作表头
        String[] fields = {"题目ID", "所属公司ID", "所属目录ID", "题目简介", "题干描述",
                "题干配图", "题目分析", "题目类型", "题目难度", "是否经典题", "题目状态", "审核状态"};
        Row row_2 = sheet.createRow(2);
        for (int i = 0; i < fields.length; i++) {
            Cell cell_2_temp = row_2.createCell(1 + i);
            cell_2_temp.setCellValue(fields[i]);
            cell_2_temp.setCellStyle(cs_field);
        }

        //设置属性值数组 用于反射
        String[] properties = {"Id", "CompanyId", "CatalogId", "Remark", "Subject", "Picture",
                "Analysis", "Type", "Difficulty", "IsClassic", "State", "ReviewStatus"};
        //制作数据区
        int row_index = 0;
        for (Question question : list) {
            int cell_index = 0;
            Row row_temp = sheet.createRow(3 + row_index++); //每次行数据填完之后 行表需要++
            for (int i = 0; i < properties.length; i++) {

                try{
                    //通过反射获取方法对象
                    Method method = Question.class.getMethod("get" + properties[i]);
                    //创建列
                    Cell cell_data = row_temp.createCell(1 + cell_index++);  //每次行数据填完之后 列需要++填充值
                    //设置值
                    cell_data.setCellValue(String.valueOf(method.invoke(question)));

                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            //将工作簿写入到流
            wb.write(os);
            //释放资源
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return os;
    }
}
